import relationalStore from '@ohos.data.relationalStore';
import promptAction from '@ohos.promptAction';
import util from '@ohos.util';
import { EMPLOYEE } from '../data/LibEmployee';

namespace DbUtil {

  export function getRdbStore(dbIndex: number, callback: (store: relationalStore.RdbStore) => void) {
    let dbName: string = `RdbTest_${dbIndex}.db`
    const STORE_CONFIG = {
      name: dbName, // 数据库文件名
      securityLevel: relationalStore.SecurityLevel.S1 // 数据库安全级别
    };

    const SQL_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)'; // 建表Sql语句
    relationalStore.getRdbStore(globalThis.context, STORE_CONFIG, (err, store) => {
      if (err) {
        console.error(`Failed to get RdbStore. Code:${err.code}, message:${err.message}`);
        return;
      }
      console.info(`Succeeded in getting RdbStore.`);
      store.executeSql(SQL_CREATE_TABLE); // 创建数据表
      // 这里执行数据库的增、删、改、查等操作
      callback(store)
    });
  }

  export function insertData(dbIndex: number) {
    getRdbStore(dbIndex, (store: relationalStore.RdbStore) => {
      const valueBucket = {
        'NAME': 'Lisa' + dbIndex,
        'AGE': 18,
        'SALARY': 100.5,
        'CODES': new Uint8Array([1, 2, 3, 4, 5])
      };
      store.insert('EMPLOYEE', valueBucket, (err, rowId) => {
        if (err) {
          console.error(`Failed to insert data. Code:${err.code}, message:${err.message}`);
          return;
        }
        let msg:string = `Succeeded in inserting data. rowId:${rowId}`
        showToast(msg)
        console.info(msg);
      })
    })
  }

  export function showToast(msg: string) {
    promptAction.showToast({ duration: 2200, message: msg })
  }

  export function queryData(dbIndex: number, callback: (list: EMPLOYEE[]) => void) {
    getRdbStore(dbIndex, (store) => {
      let predicates = new relationalStore.RdbPredicates('EMPLOYEE');
      store.query(predicates, ['ID', 'NAME', 'AGE', 'SALARY', 'CODES'], (err, resultSet) => {
        if (err) {
          console.error(`Failed to query data. Code:${err.code}, message:${err.message}`);
          return;
        }
        let resultList: EMPLOYEE[] = []
        let columnNames = resultSet.columnNames
        let rowCount = resultSet.rowCount
        showToast("查询结果行数:" + rowCount)
        while (resultSet.goToNextRow()) {
          let employee = new EMPLOYEE()
          let index = resultSet.getColumnIndex("ID")
          employee.id = resultSet.getLong(index)
          let nameIndex = resultSet.getColumnIndex("NAME")
          employee.name = resultSet.getString(nameIndex)
          let ageInex = resultSet.getColumnIndex("AGE")
          let salaryIndex = resultSet.getColumnIndex("SALARY")
          let codesIndex = resultSet.getColumnIndex("CODES")
          employee.age = resultSet.getLong(ageInex)
          employee.salary = resultSet.getDouble(salaryIndex)
          employee.codes = resultSet.getBlob(codesIndex)
          employee.itemKey = util.generateRandomUUID()
          resultList.push(employee)
        }
        if (undefined != callback) {
          callback(resultList)
        }
        console.info(`ResultSet column names: ${resultSet.columnNames}`);
        console.info(`ResultSet column count: ${resultSet.columnCount}`);
      })
    })
  }

}

export default DbUtil